package com.bobamrz.frontend;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bobamrz.hibernate.HibernateUtil;

public abstract class SuperServlet extends HttpServlet {

	private static final long serialVersionUID = -5398307002815161865L;
	private Logger log = Logger.getLogger(SuperServlet.class);
	
	@Override
	public void init() throws ServletException {
		log.debug("i am born!");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
			processGet(req, resp);
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
		} catch (Exception e) {
			try {
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
				log.error("exception caught at servlet level", e);
				
			} catch (Exception e2) {}
				RequestDispatcher dispatcher = getServletContext().
											   getRequestDispatcher("/error.html");
				dispatcher.forward(req, resp);
		} finally {
			try {
				HibernateUtil.getSessionFactory().getCurrentSession().close();
			} catch (Exception e2) {}	
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
			processPost(req, resp);
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
		} catch (Exception e) {
			try {
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
				log.error("exception caught at servlet level", e);
				
			} catch (Exception e2) {}
				RequestDispatcher dispatcher = getServletContext().
											   getRequestDispatcher("/error.html");
				dispatcher.forward(req, resp);
		} finally {
			try {
				HibernateUtil.getSessionFactory().getCurrentSession().close();
			} catch (Exception e2) {}	
		}
	}

	/**
	 * Override this
	 * @param req
	 * @param resp
	 * @throws IOException 
	 * @throws ServletException 
	 */
	protected void processPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		throw new UnsupportedOperationException();//default
	}
	
	/**
	 * Override this
	 * @param req
	 * @param resp
	 * @throws IOException 
	 * @throws ServletException 
	 */
	protected void processGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		throw new UnsupportedOperationException();//default
	}
	
}
